<template>
  <div class="new-supplier-mod">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{ $t('shop.editSupplierProd') }}
      </div>
    </div>
    <div class="info-title">
      {{ $t('shopProcess.basicInfo') }}
    </div>
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      class="form-box"
      label-width="auto"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('shop.supplierName')"
        prop="supplierName"
      >
        <span class="table-cell-text line-clamp-one">{{ dataForm.supplierName }}</span>
      </el-form-item>
    </el-form>
    <div class="info-title">
      {{ $t('shop.supplierProd') }}
    </div>
    <div style="float: left;margin: 8px 0 12px 10px">
      <div
        v-if="isAuth('multishop:supplierProd:select')"
        plain
        class="default-btn primary-btn"
        @click="selectSupplierProd"
      >
        {{ $t("shop.addProd") }}
      </div>
      <div
        v-if="isAuth('multishop:supplierProd:export')"
        class="default-btn"
        @click="getExportExcel()"
      >
        {{ $t("formData.export") }}
      </div>
      <el-tooltip
        class="item"
        :disabled="supplierProds.length === 0"
        effect="dark"
        :content="$t('shop.supplierProdImportTip')"
        placement="top"
      >
        <div
          class="default-btn"
          :class="{'disabled-btn': supplierProds.length > 0}"
          @click.stop="getUpload()"
        >
          {{ $t("product.importGoods") }}
        </div>
      </el-tooltip>
    </div>

    <div class="main-container">
      <div class="table-con">
        <el-table
          :data="supplierProds.slice((page.currentPage - 1) * page.pageSize, page.currentPage * page.pageSize)"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          :row-style="{ height:'70px'}"
          style="width: 100%;margin-left: 10px"
        >
          <el-table-column
            :label="$t('product.prodName')"
            prop="prodName"
            width="300"
            align="left"
          >
            <template #default="scope">
              <div class="df prod-info">
                <ImgShow
                  :src="scope.row.pic"
                  :img-style="{width:'60px',height:'60px'}"
                />
                <div class="text">
                  <span class="name">{{ scope.row.prodName }}</span>
                  <span class="name">{{ scope.row.skuName }}</span>
                  <span class="name">{{ scope.row.partyCode }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('shop.minOrderQuantity')"
            prop="minOrderQuantity"
            align="left"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.minOrderQuantity"
                type="number"
                style="width: 150px"
                onkeyup="value=value.replace(/[^\d]/g,'')"
                @keydown="channelInputLimit"
                @blur="minOrderQuantityBlur(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('purchase.order.purchasePrice')"
            prop="purchasePrice"
            align="left"
          >
            <template #default="scope">
              <el-input
                v-model="scope.row.purchasePrice"
                type="number"
                style="width: 150px"
                :min="0.01"
                :step="0.01"
                :precision="2"
                :max="100000000000"
                @blur="vaildPrice(scope)"
              />
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('crud.menu')"
            width="220"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  class="default-btn text-btn"
                  @click="onDelete(scope.$index)"
                >
                  {{ $t('crud.delBtn') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-size="page.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="supplierProds.length"
        @current-change="onPageChange"
      />
    </div>
    <div
      class="footer"
      style="z-index: 1"
    >
      <div class="btn">
        <div
          class="default-btn"
          @click="back()"
        >
          {{ $t("shopFeature.edit.back") }}
        </div>
        <div
          v-if="isAuth('multishop:supplierProd:update')"
          type="primary"
          class="default-btn primary-btn"
          @click="confirm()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </div>
    <!-- 供应商商品选择弹窗-->
    <supplier-prod-select
      v-if="supplierProdSelectVisible"
      ref="supplierProdSelectRef"
      @refresh-select-supplier="supplierProdSelectHandle"
    />
    <!--供应商商品导入弹窗-->
    <supplier-prod-upload
      v-if="uploadVisible"
      ref="supplierProdUploadRef"
      @refresh-data-list="getWaitingExcel"
    />
  </div>
</template>

<script setup>
import { isAuth } from '@/utils'
import SupplierProdUpload from './components/supplier-prod-upload.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const uploadVisible = ref(false)
const supplierProdSelectVisible = ref(false)
const supplierProds = ref([]) // 选择的商品
let skuIds = []
const dataForm = reactive({
  supplierId: null,
  supplierName: null,
  prodName: null,
  minOrderQuantity: 1,
  purchasePrice: 0.01,
  supplierProdId: null,
  skuId: null,
  type: null
})
const supplierProd = reactive({
  supplierId: null
})
const page = reactive({
  currentPage: 1, // 初始页
  pageSize: 10 // 每页数据大小
})

// eslint-disable-next-line no-unused-vars
const value = ref('')
const Route = useRoute()
const Router = useRouter()
onMounted(() => {
  if (Route.query.supplierId) {
    supplierProd.supplierId = Route.query.supplierId
  }
  if (Route.query.supplierName) {
    dataForm.supplierName = Route.query.supplierName
  }
  getDataList()
})

const getDataList = () => {
  http({
    url: http.adornUrl('/supplier/supplierProd/listSupplierProd'),
    method: 'get',
    params: http.adornParams({
      supplierId: supplierProd.supplierId
    })
  }).then(({ data }) => {
    supplierProds.value = data
    if (supplierProds.value) {
      supplierProds.value.forEach(row => {
        skuIds.push(row.skuId)
      })
    }
  })
}

/**
 * 校验采购价输入框
 */
const vaildPrice = (scope) => {
  const { row, $index } = scope
  const purchasePrice = row.purchasePrice
  if (!purchasePrice || purchasePrice <= 0) {
    supplierProds.value[$index].purchasePrice = 0.01
    return
  }
  if (purchasePrice > 100000000000) {
    supplierProds.value[$index].purchasePrice = 100000000000
    return
  }
  supplierProds.value[$index].purchasePrice = constrainNum(purchasePrice)
}
// 四舍五入保留2位小数
const constrainNum = (num) => {
  let result = parseFloat(num)
  result = +Number(result).toFixed(2)
  let temp = result.toString()
  const i = temp.indexOf('.')
  if (i !== -1 && temp.length <= i + 2) {
    temp += '0'
  }
  return temp
}

// 选择供应商商品
const supplierProdSelectRef = ref(null)
const selectSupplierProd = () => {
  const data = {
    supplierId: supplierProd.supplierId,
    skuIds
  }
  supplierProdSelectVisible.value = true
  nextTick(() => {
    supplierProdSelectRef.value?.init(data)
  })
}
const supplierProdSelectHandle = (prod) => {
  prod.forEach(item => {
    const param = {
      supplierId: supplierProd.supplierId,
      supplierProdId: null,
      prodId: item.prodId,
      skuId: item.skuId,
      prodName: item.prodName,
      skuName: item.skuName,
      partyCode: item.partyCode,
      pic: item.pic,
      minOrderQuantity: 1,
      purchasePrice: 0.01
    }
    supplierProds.value.push(param)
    skuIds.push(item.skuId)
  })
}
const getWaitingExcel = () => {
  getDataList(page)
}
// 跳转至导入选择
const supplierProdUploadRef = ref(null)
const getUpload = () => {
  if (supplierProds.value.length > 0) {
    return
  }
  uploadVisible.value = true
  const id = supplierProd.supplierId
  nextTick(() => {
    supplierProdUploadRef.value?.init(id)
  })
}
const getExportExcel = () => {
  ElMessageBox.confirm(`${$t('shop.exportProdTip')}`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/supplier/supplierProd/exportSupplierProd'),
      method: 'get',
      params: http.adornParams({
        supplierId: supplierProd.supplierId
      }),
      responseType: 'blob' // 解决文件下载乱码问题
    }).then(({ data }) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
      const fileName = $t('shop.exProdFileName')
      const elink = document.createElement('a')
      if ('download' in elink) { // 非IE下载
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    })
  })
}
const confirm = () => {
  http({
    url: http.adornUrl('/supplier/supplierProd'),
    method: 'put',
    data: supplierProds.value,
    params: {
      supplierId: supplierProd.supplierId
    }
  }).then(() => {
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1000
    })
    refreshChange()
  })
}
/**
 * 删除已选择的商品项
 * @param index 当前商品项在当前页的位置
 */
const onDelete = (index) => {
  // 页码-1 * 页面大小 + index = 当前删除项在数组中的位置
  supplierProds.value.splice(((page.currentPage - 1) * page.pageSize) + index, 1)
  // 判断当前页码是否超过删除后的页码大小
  if (page.currentPage > ((supplierProds.value.length - 1) / page.pageSize + 1)) {
    page.currentPage = --page.currentPage || 1
  }
  skuIds = []
  if (supplierProds.value) {
    supplierProds.value.forEach(row => {
      skuIds.push(row.skuId)
    })
  }
}
const back = () => {
  // Router.push('/stock-supplierProd')
  Router.go(-1)
}
const refreshChange = () => {
  skuIds = []
  getDataList()
}
const onPageChange = (val) => {
  page.currentPage = val
}
const channelInputLimit = (e) => {
  const key = e.key
  if (key === '.') {
    e.returnValue = false
    return false
  }
  return true
}
const minOrderQuantityBlur = (item) => {
  if (item.minOrderQuantity < 1 || item.minOrderQuantity > 1000000000) item.minOrderQuantity = 1
}

</script>

<style scoped>
div :deep(.is-success .el-input-number__decrease),
div :deep(.is-success .el-input-number__increase),
div :deep(.is-error .el-input-number__decrease),
div :deep(.is-error .el-input-number__increase) {
  right: 1px !important;
}
div :deep(.el-date-editor .el-range-separator) {
  width: 8%;
}
.form-box {
  margin-left: 10px;
}
.new-supplier-mod::after{
  content: '';
  display: block;
  width: 100%;
  height:52px ;
}
.new-supplier-mod .footer {
  height: 52px;
  position: fixed;
  bottom: 0;
  width: 100%;
  display: flex;
  /* justify-content: center; */
  align-items: center;
  box-shadow: 0 -3px 5px #eee;
  background: #FFF;
}
.new-supplier-mod .footer .btn {
  width: 80%;
  display: flex;
  justify-content: center;
}
.info-title {
  border-bottom: solid 1px #ebedf0;
  margin: 8px 0 12px 10px;
  line-height: 25px;
  color: #606266;
}
.prod-info {
  display: flex;
  align-items: center;
}
.prod-info .text {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  margin-left: 10px;
  width: 170px;
}
.prod-info .text .name{
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.new-supplier-mod .footer .default-btn {
  height: 32px;
  line-height: 32px;
}
@media (max-width: 1440px){
  :deep(.el-card__body) {
    padding-bottom: 40px !important;
  }
}
</style>
